<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="100px" class="dialog-form">
      <el-row>
        <!-- 项目编号 -->
        <el-col :span="12">
          <el-form-item label="项目编号" prop="productNumber">
            <el-select
                v-model="dataForm.productNumber"
                placeholder="请选择项目编号"
                class="label_len"
                @change="handleProjectChange"
                :disabled="selectDis">
              <el-option
                  v-for="item in projectList"
                  :key="item.prProjectNumber"
                  :label="item.prProjectNumber + ' ' + item.prProjectName"
                  :value="item.prProjectNumber">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 测定日期 -->
        <el-col :span="12">
          <el-form-item label="测定日期" prop="dataTime">
            <el-date-picker v-model="dataForm.dataTime" type="datetime" placeholder="请选择测定日期"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table :data="tableData" border style="margin-top: 20px;">
        <el-table-column label="序号" prop="number" width="80"></el-table-column>
        <el-table-column label="检查项目" prop="project" width="200"></el-table-column>
        <el-table-column label="单位" prop="unit" width="100"></el-table-column>
        <el-table-column label="设计值" prop="valueTa" width="200"></el-table-column>
        <el-table-column label="限制范围" prop="rangeTa" width="200"></el-table-column>
        <el-table-column label="检查方法" prop="methodTa" width="150"></el-table-column>
        <el-table-column label="核测结果" prop="verificationResult" width="150">
          <template slot-scope="scope">
            <el-input v-model="scope.row.verificationResult" placeholder="请输入核测结果" @input="checked()"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="一致性判定" prop="consistencyJudgmentResult" width="150">
          <template slot-scope="scope">
            <el-input v-model="scope.row.consistencyJudgmentResult" placeholder="请输入一致性判定"></el-input>
          </template>
        </el-table-column>
      </el-table>

      <!-- 综合判定 -->
      <el-form-item label="综合判定" prop="consistencySynthesisDecision" style="margin-top: 20px;">
        <el-radio-group v-model="dataForm.consistencySynthesisDecision">
          <el-radio label="合格">合格</el-radio>
          <el-radio label="不合格">不合格</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 提示信息 -->
      <div class="form-notes" style="margin-top: 20px; font-size: 14px; color: #f56c6c;">
        <p>注：1.工作状态指样机在硬化检测场地上的实际作业状态。</p>
        <p>2.一致性判定合格为“+”，不合格为“-”。</p>
      </div>
    </el-form>

    <!-- 底部按钮 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false" size="medium">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" size="medium">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>

export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: 0,
        dataTime: '',
        productNumber: '',
        consistencySynthesisDecision: '',
        inspector: '',
        notekeeper: '',
        checker: '',
        pdfPath: '',
        wordPath: '',
        status: '',
        userId: '',
        consCheckRecordInfoList: this.tableData
      },
      projectList: [],
      tableData: [],
      selectDis: false,
      defaultTableData: [
        { number: 1,key:'model', project: '型号名称', unit: '/', valueTa: '', rangeTa: '一致', methodTa: '核对', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 2,key:'construction', project: '结构型式（圆梁型、框架型）', unit: '/', valueTa: '', rangeTa: '一致', methodTa: '核对', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 3,key:'outline', project: '整机外形尺寸（长×宽×高）', unit: 'mm', valueTa: '', rangeTa: '允许偏差为5%', methodTa: '测量', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 4,key:'operange', project: '工作幅宽', unit: 'cm', valueTa: '', rangeTa: '允许偏差为3%', methodTa: '测量', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 5,key:'cutter', project: '刀轴型式（单轴型、双轴型）', unit: '/', valueTa: '', rangeTa: '一致', methodTa: '核对', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 6,key:'cutterconn', project: '刀轴连接型式（接盘式、花键式）', unit: '/', valueTa: '', rangeTa: '一致', methodTa: '核对', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 7,key:'drive', project: '传动型式（中间传动、侧边传动）', unit: '/', valueTa: '', rangeTa: '一致', methodTa: '核对', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 8,key:'transportation', project: '运输方式（普通型、折叠型）', unit: '/', valueTa: '', rangeTa: '一致', methodTa: '核对', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 9,key:'gearbox', project: '变速箱档位数（变速旋耕机）', unit: '个', valueTa: '', rangeTa: '一致', methodTa: '核对', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 10,key:'knife', project: '刀辊设计转速', unit: 'r/min', valueTa: '', rangeTa: '一致', methodTa: '核对', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 11,key:'knifeMax', project: '刀辊最大回转半径', unit: 'mm', valueTa: '', rangeTa: '允许偏差为3%', methodTa: '测量', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 12,key:'knifenum', project: '刀辊总安装刀数', unit: '把', valueTa: '', rangeTa: '一致', methodTa: '核对', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 13,key:'tooltype', project: '旋耕刀型号', unit: '/', valueTa: '', rangeTa: '一致', methodTa: '核对', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 14,key:'depthlimit', project: '限深装置型式（限深板、限深轮）', unit: '/', valueTa: '', rangeTa: '核对', methodTa: '核对', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 15,key:'suppress', project: '镇压型式（拖板、镇压辊）', unit: '/', valueTa: '', rangeTa: '一致', methodTa: '核对', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 16,key:'power', project: '配套拖拉机标定功率', unit: 'kW', valueTa: '', rangeTa: '一致', methodTa: '核对', verificationResult: '', consistencyJudgmentResult: '' },
        { number: 17,key:'rotate', project: '配套拖拉机动力输出轴转速', unit: 'r/min', valueTa: '', rangeTa: '一致', methodTa: '核对', verificationResult: '', consistencyJudgmentResult: '' }
      ],

      dataRule: {
        dataTime: [
          { required: true, message: '检测日期不能为空', trigger: 'blur' }
        ],
        productNumber: [
          { required: true, message: '产品编号不能为空', trigger: 'blur' }
        ],
        consistencySynthesisDecision: [
          { required: true, message: '一致性综合决定(合格、不合格)不能为空', trigger: 'blur' }
        ],
        inspector: [
          { required: true, message: '检测人不能为空', trigger: 'blur' }
        ],
        notekeeper: [
          { required: true, message: '记录人不能为空', trigger: 'blur' }
        ],
        checker: [
          { required: true, message: '核校人不能为空', trigger: 'blur' }
        ],
        pdfPath: [
          { required: true, message: 'pdf路径不能为空', trigger: 'blur' }
        ],
        wordPath: [
          { required: true, message: 'word路径不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '审核状态不能为空', trigger: 'blur' }
        ],
        userId: [
          { required: true, message: '用户ID不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  mounted(){
    this.getprojectList()
  },
  methods: {
    checked() {
      let count = 0;
      console.log("开始自动赋值")
      this.defaultTableData.forEach(item => {
        // 核查测量方法
        if (item.methodTa === '核对') {
          console.log("核对")
          // 核对方法：检查valueTa和verificationResult是否一致
          if (item.valueTa.trim() === item.verificationResult.trim()) {
            item.consistencyJudgmentResult = '+';
          } else {
            item.consistencyJudgmentResult = '-';
          }
        } else if (item.methodTa === '测量') {
          console.log("测量")
          // 测量方法：需要检查数值是否在范围内
          let range = item.rangeTa.trim();
          let value = item.valueTa.trim();
          let verificationResult = item.verificationResult.trim();

          // 如果valueTa和verificationResult是类似"1010X1755X890"的格式
          if (value && verificationResult) {
            let valueArray = value.split('X').map(num => parseFloat(num));  // 将valueTa拆分并转换为数字数组
            let verificationArray = verificationResult.split('X').map(num => parseFloat(num));  // 同理拆分并转换

            if (valueArray.length === verificationArray.length && valueArray.every(val => !isNaN(val))) {
              let isValid = true;

              for (let i = 0; i < valueArray.length; i++) {
                let value = valueArray[i];
                let verificationValue = verificationArray[i];

                // 偏差范围
                if (range) {
                  let match = range.match(/允许偏差为(\d+)%/);
                  if (match) {
                    let allowedDeviation = parseFloat(match[1]);

                    // 计算偏差范围
                    let minValue = verificationValue * (1 - allowedDeviation / 100);
                    let maxValue = verificationValue * (1 + allowedDeviation / 100);

                    // 检查value是否在允许的偏差范围内
                    if (value < minValue || value > maxValue) {
                      isValid = false;
                      break;
                    }
                  }
                }
              }

              item.consistencyJudgmentResult = isValid ? '+' : '-';
            } else {
              item.consistencyJudgmentResult = '-';
            }
          } else {
            item.consistencyJudgmentResult = '-';
          }
        } else {
          item.consistencyJudgmentResult = '-';
        }

        // 统计通过的项数
        if (item.consistencyJudgmentResult === '+') {
          count++;
        }
      });

      console.log("通过的项数：" + count);

      // 合格标准：至少17项符合要求
      if (count >= 17) {
        this.dataForm.consistencySynthesisDecision = '合格';
      } else {
        this.dataForm.consistencySynthesisDecision = '不合格';
      }
    },

    //获取项目列表
    getprojectList() {
      this.$http({
        url: this.$http.adornUrl(`/reportapproval/product/getProjectNumber`),
        method: 'post',
        data: this.$http.adornData({
        })
      }).then((data) => {
        if (data && data.code === 0) {
          console.log(data.productList)
          this.projectList = data.productList
        } else {
          this.$message.warning(data.msg)
        }
      })
    },
    //选中项目编号，拉取对应的valueTa值
    handleProjectChange(value){
      this.$http({
        url: this.$http.adornUrl(`/reportapproval/productspecification/getInfo/${value}`),
        method: 'get',
        data: this.$http.adornData({

        })
      }).then((data) => {
        if (data && data.code === 0) {
          const productList = data.productSpecification; // 返回的产品规格数据
          if (productList.length > 0){
            this.tableData = this.defaultTableData
          }
          const updatedTableData = this.tableData.map((item) => {
            // 找到对应的 characteristic, 并更新 valueTa
            const matchingProduct = productList.find(product => product.characteristic === item.key);
            if (matchingProduct) {
              // 更新相应的 valueTa 值
              item.valueTa = matchingProduct.designValue;
            }
            return item;
          });
          if(updatedTableData.length > 0){
            this.tableData = updatedTableData; // 更新表格数据
          }else{
            this.tableData = []
          }
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    init(id) {
      this.dataForm.id = id || 0
      this.visible = true
      this.selectDis = false
      this.tableData = []
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/reportapproval/conscheckrecord/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then((data) => {
            if (data && data.code === 0) {
              this.dataForm.dataTime = data.consCheckRecord.dataTime
              this.dataForm.productNumber = data.consCheckRecord.productNumber
              this.dataForm.consistencySynthesisDecision = data.consCheckRecord.consistencySynthesisDecision
              this.dataForm.inspector = data.consCheckRecord.inspector
              this.dataForm.notekeeper = data.consCheckRecord.notekeeper
              this.dataForm.checker = data.consCheckRecord.checker
              this.dataForm.pdfPath = data.consCheckRecord.pdfPath
              this.dataForm.wordPath = data.consCheckRecord.wordPath
              this.dataForm.status = data.consCheckRecord.status
              this.dataForm.userId = data.consCheckRecord.userId
              this.dataForm.consCheckRecordInfoList = data.consCheckRecord.consCheckRecordInfoList
              this.tableData = data.consCheckRecord.consCheckRecordInfoList
              this.selectDis = true
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/reportapproval/conscheckrecord/${!this.dataForm.id ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'dataTime': this.dataForm.dataTime,
              'productNumber': this.dataForm.productNumber,
              'consistencySynthesisDecision': this.dataForm.consistencySynthesisDecision,
              'inspector': this.dataForm.inspector,
              'notekeeper': this.dataForm.notekeeper,
              'checker': this.dataForm.checker,
              'pdfPath': this.dataForm.pdfPath,
              'wordPath': this.dataForm.wordPath,
              'status': this.dataForm.status,
              'userId': this.dataForm.userId,
              'consCheckRecordInfoList': this.tableData
            })
          }).then((data) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.warning(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
<style scoped>
.dialog-form {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 20px; /* 设置每个表单项之间的间距 */
}

.el-row {
  margin-bottom: 20px; /* 行间距 */
}

.el-table {
  margin-top: 20px;
}

.form-notes {
  margin-top: 20px;
  font-size: 14px;
  color: #f56c6c;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 20px;
}

.el-button {
  margin-left: 10px; /* 按钮之间的间距 */
}
</style>
